package dao

import (
	"sort"
	"goBasic/zhangxiaokun/bean"
	//"fmt"
)

type UserDao struct {
	UsersMap map[int]*bean.User		//存放用户
	maxId int					//记录当前最大用户id, 用于自增主键id
}

/**
初始化
 */
func (userDao *UserDao) init()  {
	if userDao.UsersMap == nil {
		userDao.UsersMap = make(map[int]*bean.User)
		userDao.maxId = 0
	}
}

/*
查询
 */
func (userDao *UserDao) GetUser(id int) *bean.User {
	return userDao.UsersMap[id]
}

/**
按账户名查询
 */
func (userDao *UserDao) GetUserByUserName (userName string) *bean.User {
	userList := userDao.GetAllUser()

	//fmt.Println(userList)

	for _,user := range userList{
		if user.UserName == userName {
			return user
		}
	}

	return nil
}

/*
更新
 */
func (userDao *UserDao) UpdateUser(user *bean.User) {
	id := user.UserId
	userDao.UsersMap[id] = user
}

/*
保存
 */
func (userDao *UserDao) SaveUser(user *bean.User) (userId int) {
	if userDao.UsersMap == nil {
		userDao.init()
	}
	userDao.maxId++
	user.UserId = (userDao.maxId)
	userDao.UsersMap[user.UserId] = user

	return user.UserId
}

/*
删除
 */
func (userDao *UserDao) Delete(userId int) {
	delete(userDao.UsersMap, userId)
}

/*
获取所有用户
 */
func (userDao *UserDao) GetAllUser() []*bean.User {
	userMap := userDao.UsersMap

	userList := make([]*bean.User, 0, len(userMap))
	userIdList := make([]int, 0, len(userMap))


	//取出userId
	for index,_ := range userDao.UsersMap{
		userIdList = append(userIdList, index)
	}
	//排序
	sort.Ints(userIdList)

	//取出user
	for _,userId := range userIdList {
		user := userMap[userId]
		userList = append(userList, user)
	}

	return userList
}



/**
存钱
 */
func (useDao *UserDao) Deposit()  {

}
